package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author fengzhu
 * @since 2024-10-10
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishService  setmealDishService;
    /**
     * 更新状态和id
     * @param status
     * @param ids
     */
    @Override
    public void updateStatusById(int status, List<Long> ids) {
        //存到我们的数据库里面mapper
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        //
        wrapper.in(Setmeal::getId,ids) //更新id属于ids的列表 where id in
                .set(Setmeal::getStatus,status);
        setmealMapper.update(null,wrapper);
        //null的意思是我们不更新整个实体，只更新某个字段
    }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
        Setmeal setmeal =this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);

        //从dish里面查菜品
        LambdaUpdateWrapper<SetmealDish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> list =setmealDishService.list(wrapper);
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    @Override
    public void updateWithSetmealDish(SetmealDto setmealDto,Long empid) {
        //先更新setmeal表
        this.updateById(setmealDto);

        //清理setmeal表
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(wrapper);

        //
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList =setmealDishList.stream().map((item)->{
            item.setSetmealId(String.valueOf(setmealDto.getId()));
            item.setCreateUser(empid);
            item.setUpdateUser(empid);
            return item;
        }).toList();
        setmealDishService.saveBatch(setmealDishList);
    }


}
